﻿using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace lottery.admin
{
    public class SeedData
    {
        private static IConfiguration Configuration { get; set; }

        public async static Task EnsureSeedData(IServiceProvider serviceProvider)
        {
            Console.WriteLine("Seeding database...");

            using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
                var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
                Configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
                try
                {
                    await SetAdmin(userManager, roleManager);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("SetAdmin Fail:" + ex.Message);
                }
            }
        }

        public async static Task SetAdmin(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            string email = Configuration["MasterAccount:Email"];
            string password = Configuration["MasterAccount:Password"];
            var user = await userManager.Users.SingleOrDefaultAsync(d => d.Email == email);
            if (user == null)
            {
                user = new IdentityUser { UserName = email, Email = email };
                var result = await userManager.CreateAsync(user, password);
                if (!result.Succeeded)
                    throw new Exception("userManager.Create: " + result.Errors.First().Description);
            }

            var roles = await userManager.GetRolesAsync(user);
            if (roles.Contains("Admin")) return;

            var role = await roleManager.FindByNameAsync("Admin");
            if (role == null)
            {
                var rresult = await roleManager.CreateAsync(new IdentityRole { Name = "Admin" });
                if (!rresult.Succeeded)
                    throw new Exception("roleManager.Create: " + rresult.Errors.First().Description);
            }

            var uresult = await userManager.AddToRoleAsync(user, "Admin");
            if (!uresult.Succeeded)
                throw new Exception("userManager.AddToRole: " + uresult.Errors.First().Description);
        }
    }
}
